<template>
  <div class="statistics_page">
    <div class="text-right statistics_page_header">
	  <el-button class="button_list" type="primary" @click="go_add_item">添加组件</el-button>

      <el-button class="button_list" type="primary" @click="saveTemplate">保存模板</el-button>
    </div>

    <div class="grid_box" v-loading="statistics_page_loading">
      <div class="left">
        <grid-layout
          ref="gridLayoutref"
          v-model:layout="layout"
          :col-num="12"
          :row-height="30"
          :is-draggable="true"
          :is-resizable="true"
          :is-mirrored="false"
          :vertical-compact="true"
          :margin="[20, 20]"
          :use-css-transforms="true"
		  
        >
          <grid-item
            class="grid-item"
            ref="gridItem"
            v-for="(item,index) in layout"
            :x="item.x"
            :y="item.y"
            :w="item.w"
            :h="item.h"
            :i="item.i"
            :key="item.i"
            :minW="item.minW"
            :minH="item.minH"
            :static="item.static"
			@resized="resizedEvent"
            dragIgnoreFrom=".grid_content"
			
          >
            <div class="grid_every_box">
              <div :class="'grid_header ' + item.class">
                <div class="grid_header_l">
                  {{ item.name }}
                </div>
                <div class="grid_header_r">
				  <!-- 删除icon -->
                  <span v-if="layout.length>1" class="btn close" @click="delItem(item)"
                    ><el-icon><Delete /></el-icon
                  ></span>

				  
				  <span  class="btn"><el-icon><Refresh /></el-icon></span>

 				  <!-- 图标 -->
                  <span v-if="item.i == 0" class="btn close"
                    ><el-icon><DataLine /></el-icon
                  ></span>

 				  <!-- 点点点 -->
				  <el-dropdown v-if="item.i == 0" >
					<span class="el-dropdown-link btn">
						<el-icon><MoreFilled /></el-icon>
					</span>
					<template #dropdown>
					<el-dropdown-menu>
						<el-dropdown-item>Action 1</el-dropdown-item>
						<el-dropdown-item>Action 2</el-dropdown-item>
						<el-dropdown-item>Action 3</el-dropdown-item>
						<el-dropdown-item disabled>Action 4</el-dropdown-item>
						<el-dropdown-item divided>Action 5</el-dropdown-item>
					</el-dropdown-menu>
					</template>
				</el-dropdown>
                </div>
              </div>
			 

              <div class="grid_content" >
				<div v-if="item.i==0" class="eCharts_header">
					<div class="eCharts_header_l">
						二级标题/tab标签
					</div>
					<div class="eCharts_header_r">
						<el-select @change="change_echarts_data(item)" class="eCharts_select" v-model="value" placeholder="Select" style="width: 240px">
						<el-option
						v-for="item in options"
						:key="item.value"
						:label="item.label"
						:value="item.value"
						:disabled="item.disabled"
						/>
					</el-select>

					<el-select class="eCharts_select" v-model="value1" placeholder="Select" style="width: 240px">
						<el-option
						v-for="item in options"
						:key="item.value"
						:label="item.label"
						:value="item.value"
						:disabled="item.disabled"
						/>
					</el-select>
					</div>
				
				</div>
				<div class="grid_eCharts_content" style="width: 100%; height: 100%; flex: 1">
					<ECharts 
					     v-if="item.status"
						:ref="(el:refItem) => handleSetFromMap(el, item)"
						:option="item.charts"
					></ECharts>

				</div>


               

                <!-- <template v-if="item.i == 0">
                  <canvas ref="echartsRef1" id="sd" style="width: 100%; height: 100%">gamePlay</canvas>
                </template> -->
              </div>
            </div>
          </grid-item>
        </grid-layout>
        <!-- <div ref="echartsRef" style="height: 400px; width: 500px">gamePlay</div> -->
        <!-- <canvas ref="echartsRef1" style="height: 400px; width: 500px">gamePlay</canvas> -->
      </div>
    </div>


	  <!-- 新增抽屉start -->

	  <el-dialog modal-class="merak_modal" v-model="addtemolates_modal" direction="rtl"
                :close-on-click-modal="false" :close-on-press-escape="false"  width="700">
                <template #header>
                    <div class="merak_modal_title">添加工作台组件</div>
                </template>
                <div  >
                   <el-row :gutter="40">
					<el-col :span="12" v-for="template_every in templates_arr">
						<div class="template_every">
							<div class="template_every_l">
								<div class="tit">
									{{ template_every.tit}}
								</div>
								<div class="desc">
									{{ template_every.desc }}
								</div>
								
							</div>
							<div class="template_every_r">
								<span>
									<el-button @click="add_item_page(template_every)" :disabled="template_every.is_inpage" size="small" type="default">
										
										{{ template_every.is_inpage?'已存在':'添加组件' }}
									</el-button>

								</span>
							</div>

						</div>

					</el-col>
				

				   </el-row>

                </div>


             
            </el-dialog>

            <!-- 新增抽屉end -->

  </div>
</template>

<script setup lang="ts" name="caseTwo">
import { useRouter } from "vue-router";
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from "vue";
import echarts, { ECOption } from "@/components/ECharts/config";
import ECharts from "@/components/ECharts/index.vue";
import Item from "@/components/MerakCollapse/Item.vue";
import { ElInput, ElScrollbar, ElTree, ElTabs, ElTabPane } from "element-plus";
import { set } from "nprogress";
import {saveStatistics,getStatistics} from "@/api/modules/personalManagementApi/holiday";
 
import {
    moreConfirm,
    confirmWarningMsg,
    successMsg,
    warnMsg,
    failMsg,
    confirmSuccessMsg,
    delConfimMsg
  } from "@/utils/messageUtils";

const router = useRouter();
const goPage = () => {
  router.push("/caseThree/index");
};


const handleScroll = (event) => {
  // 处理滚动事件
  console.log(event.target.scrollTop);
	var statistics_page_header=document.querySelector('.statistics_page_header');

  if(event.target.scrollTop>100){
	statistics_page_header.className="text-right statistics_page_header fixed_header"
  }else{
	statistics_page_header.className="text-right  statistics_page_header"
  }
};

const statistics_page_loading=ref(true)
onMounted(() => {
	var elmain=document.querySelector('.el-main');
	elmain.addEventListener('scroll', handleScroll);

	getStatisticsFun()
 });


 
 const getStatisticsFun=()=>{
	var onecharts= layout.value[0].charts;
	var twocharts= layout.value[1].charts;
	var eightcharts= layout.value[8].charts;
	
	getStatistics({"route":"TEST"}).then(res => {
		statistics_page_loading.value=false;
         if (res.code == ResultEnum.SUCCESS) {
             console.log(res.data)
			 layout.value=res.data;
			 
			 layout.value[0].charts=onecharts;
			 layout.value[0].status=true;

			 layout.value[1].charts=twocharts;
			 layout.value[1].status=true;

			 layout.value[8].charts=eightcharts;
			 layout.value[8].status=true;
			 console.log( layout.value[0])

			 layout.value.forEach((item,index)=>{
				if(item.i==1 || item.i==0 || item.i==8){

				}else{
					console.log(item.w)
					if(item.w>2){
						item.charts=twocharts;
						item.status=true;
					}else{
						item.charts={};
						item.status=false;
					}
					
				}
			 })



        }
    })
 }
 const saveTemplate=()=>{
	console.log(layout.value)
	var postlayout=JSON.parse(JSON.stringify(layout.value))
	postlayout.forEach(item=>{
		item.charts={};
		item.status=false;
	})

	
	saveStatistics({"route":"TEST","config":layout.value}).then(res => {
                if (res.code == ResultEnum.SUCCESS) {
                    successMsg('保存成功');

                }
    })


}




const addtemolates_modal=ref(false);
const go_add_item=()=>{
	addtemolates_modal.value=true;
}

const gridLayoutref=ref();
const add_item_page=(alert_item)=>{
	console.log(alert_item)
	console.log(layout.value)

	let maxValueY = null;
	layout.value.forEach((item, index) => {
			console.log(item.y);
			var cury=item.y;
			if (maxValueY === null || cury > maxValueY) {
				maxValueY = cury;
			}
	});


	console.log(maxValueY)


	var maxValueX=0;
	var last_w=layout.value[layout.value.length-1].w;
	console.log(last_w)
	if(12-last_w>5){
		maxValueX=12-last_w;
	}
	
	var new_obj= {
    charts: {
      title: {
        text:alert_item.tit,
		textStyle:{
			fontSize:14
		},
      },
      tooltip: {},
      legend: {
        data: ["订单额"]
      },
      xAxis: {
        data: ["衬衫", "羊毛衫", "雪纺衫" ]
      },
      yAxis: {},
      series: [
        {
          name: "销量",
          type: "bar",
          data: [5, 20, 36]
        }
      ]
    },
    x:0,
    y: maxValueY,
    w: 6,
    h: 8,
    i:alert_item.id,
    class: "has_blue_line",
    name: alert_item.tit,
    minW: "",
    minH: "",
    maxW: "",
    maxH: "",
	status:true
	
  }
  console.log(new_obj)
  layout.value.push(new_obj)
  layoutUpdateFun()
  addtemolates_modal.value=false;
  alert_item.is_inpage=true;	
}



// 切换下拉框,更新图表
const change_echarts_data=(item)=>{
	item.charts={
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
        orient: 'vertical',
        left: 10,
        data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
    },
    series: [
        {
            name: '访问来源',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '30',
                    fontWeight: 'bold'
                }
            },
            labelLine: {
                show: false
            },
            data: [
                {value: 335, name: '直接访问'},
                {value: 310, name: '邮件营销'},
                {value: 234, name: '联盟广告'},
                {value: 135, name: '视频广告'},
                {value: 1548, name: '搜索引擎'}
            ]
        }
    ]
}


}

const layoutUpdateFun=()=>{
	gridLayoutref.value.layoutUpdate();
	gridLayoutref.value.updateHeight();
}


const echartsRefMap = ref({});
const handleSetFromMap = (el: refItem, item: number) => {
  if (el) {
    echartsRefMap.value[`echarts_Ref_${item.i}`] = el;
  }
}

const templates_arr=ref([
	{
		tit:'在售商品货号',
		desc:'提供个人范围内任务、代码相关的统计数据',
		is_inpage:true,
		id:'11'
	},
	{
		tit:'在售折扣商品货号',
		desc:'在售品类、代码相关的统计数据',
		is_inpage:false,
		id:'12'
	},
	{
		tit:'企发销售属性',
		desc:'在售品类、代码相关的统计数据',
		is_inpage:false,
		id:'13'
	},
	{
		tit:'电子标签申请',
		desc:'在售品类、代码相关的统计数据',
		is_inpage:false,
		id:'14'
	},
	{
		tit:'在售折扣商品货号',
		desc:'在售品类、代码相关的统计数据',
		is_inpage:false,
		id:'15'
	},
])

const value = ref('Option1')
const value1 = ref('Option2')
const options = [
  {
    value: 'Option1',
    label: '全站',
  },
  {
    value: 'Option2',
    label: '俄境内标准订单',
  },
  {
    value: 'Option3',
    label: '跨境直供',
  },
  {
    value: 'Option4',
    label: '跨境拼单',
  },
  {
    value: 'Option5',
    label: 'Option5',
  },
]


const layout = ref([
  {
    charts: {
      title: {
        text: "ECharts",
		textStyle:{
			fontSize:14
		},
      },
      tooltip: {},
      legend: {
        data: ["销量"]
      },
      xAxis: {
        data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
      },
      yAxis: {},
      series: [
        {
          name: "销量",
          type: "bar",
          data: [5, 20, 36, 10, 10, 20]
        }
      ]
    },
    x: 0,
    y: 0,
    w: 8,
    h: 10,
    i: "0",
    class: "has_blue_line",
    name: "销售额",
    minW: "",
    minH: "",
    maxW: "",
    maxH: "",
	 activeName:'first'
  },
  {   
	charts:{
  title: {
    text: 'Chart',
	textStyle:{
			fontSize:12
		}
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['Email', 'Union Ads', 'Video Ads']
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: 'Email',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [120, 132, 101, 134, 90, 230, 210]
    },
    {
      name: 'Union Ads',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [220, 182, 191, 234, 290, 330, 310]
    },
    {
      name: 'Video Ads',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [150, 232, 201, 154, 190, 330, 410]
    }
    
    
  ]
 
},x: 8, y: 0, w: 4, h: 10, i: "1", minW: "", minH: "", name: "订单量", class: "", maxW: "", maxH: "" },
  {
    x: 0,
    y: 10,
    w: 2,
    h: 5,
    i: "2",
    name: "在售品类",
    class: "",
    minW: "",
    minH: "",
    maxW: "",
    maxH: ""
  },
  { x: 2, y: 0, w: 2, h: 5, i: "3", name: "我有最小宽度和最小高度", class: "", minW: 1, minH: 3, maxW: "", maxH: "" },
  { x: 4, y: 0, w: 2, h: 5, i: "4", name: "", class: "", name: "在售品类", minW: "", minH: "", maxW: "", maxH: "" },
  { x: 6, y: 0, w: 3, h: 5, i: "5", class: "", minW: "", name: "在售对象", minH: "", maxW: "", maxH: "" },
  { x: 9, y: 0, w: 3, h: 5, i: "6", name: "在售商品型号", class: "has_blue_line", minW: "", minH: "", maxW: "", maxH: "" },
  { x: 0, y: 5, w: 3, h: 6, i: "7", name: "我有最大宽度和最大高度", class: "", minW: "", minH: "", maxW: 10, maxH: 5 },
  {
	charts:{
    xAxis: {
        type: 'category',
        data: ['Mon', 'Tue']
    },
    yAxis: {
        type: 'value'
    },
    series: [{
        data: [45, 60,80],
        type: 'line'
    }]
}, x: 3, y: 5, w: 3, h: 6, i: "8", class: "", name: "SPU上架", minW: "", minH: "", maxW: "", maxH: "" },
  { x: 6, y: 15, w: 3, h: 6, i: "9", class: "",  name: "在售商品型号", minW: "", minH: "", maxW: "", maxH: "" },
  { x: 9, y: 4, w: 3, h: 6, i: "10", class: "", name: "在售商品型号", minW: "", minH: "", maxW: "", maxH: "" }
]);
// static: true,
const delItem = layout_item => {

	delConfimMsg({
      callback: val => {
        if (val == "confirm") {
			layout.value.forEach((item, index) => {
			console.log(item, index);
			if (item.i == layout_item.i) {
			console.log("删除");
			layout.value.splice(index, 1);
			}
		});

		
		templates_arr.value.forEach((item, index) => {
			
			if (item.id == layout_item.i) {
				item.is_inpage=false;
			}
		});
		console.log(templates_arr.value)

		layoutUpdateFun()

        }
      }
    });
};

const draggableStart = (id: string) => {
  console.log("拖拽开始", id);
};

const draggableHandle = (id: string, data: LayoutItem) => {
  console.log("拖拽中", id, data);
};

const resizedEvent = (i, newX, newY, newHPx, newWPx) => {
	const msg = "RESIZED i=" + i + ", X=" + newX + ", Y=" + newY + ", H(px)=" + newHPx + ", W(px)=" + newWPx;
    console.log(msg);

	
	console.log(echartsRefMap.value[`echarts_Ref_${i}`])
	echartsRefMap.value[`echarts_Ref_${i}`].resize();


};


 
</script>

<style scoped lang="scss">
@import "./index.scss";


.text-right {
  text-align: right;
}
.statistics_page_header{
	position: sticky;
    top:0;
	left:0;
	padding:10px 0;
	z-index:3;

}
.statistics_page_header.fixed_header{
	background-color: var(--background-color, #fff);
    box-shadow: 0 4px 8px -2px rgba(9, 30, 66, .1);
}
.grid-item {
  background-color: #fff;
  border-radius: 6px;
  box-shadow: inset 0 0 0 1px #ecedf0;
  display: flex;
  flex: auto;
  flex-direction: column;
  height: 100%;
  position: relative;
  overflow: hidden;
}
.grid_every_box {
  display: flex;
  flex: auto;
  flex-direction: column;
  height: 100%;
}
.grid_header {
  position: relative;
  display: flex;
  justify-content: space-between;
  padding: 10px;
  .grid_header_l {
    padding: 10px;
  }
  .grid_header_r {
    position: relative;
    z-index: 2;
    padding: 10px;
    cursor: pointer;
    color: #909aaa;
    .btn {
      font-size: 18px;
      padding: 5px;
      margin-left: 8px;
      border-radius: 4px;
      line-height: 1;
      padding-bottom: 2px;
    }
    .btn:hover {
      background-color: #ecedf0;
    }
  }
}
.grid_content {
  padding: 5px 20px;
  width: 100%;
  box-sizing: border-box;
  height: 100%;
  flex: 1;
  display: flex;
  height: 100%;
  flex-direction: column;
  .eCharts_header{
	display: flex;
	justify-content: space-between;
	padding-bottom: 20px;
	
  }

}
.grid_header.has_blue_line::before {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  border: 2px solid rgb(44, 126, 248);
}
.vue-grid-item.vue-grid-placeholder {
  background: red;
  opacity: 0.2;
  transition-duration: 100ms;
  z-index: 2;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
.el-dropdown span{
	position: relative;
	top:-6px;
}
.el-tabs__content{
	display: none;
}
.template_every{
	border: 1px dashed #c2d6ff;
    border-radius: 6px;
    display: flex;
	margin-bottom:20px;

    padding: 12px 16px;
	.template_every_l{
		width:60%;
		.tit{
		font-size: 16px;
		margin-bottom: 20px;
		}
		.desc{
			font-size: 12px;
			color:#909aaa;
		}
	}
	.template_every_r{
		flex:1;
		text-align: right;
	}
	
}



</style>
<style>
.vue-grid-item.vue-grid-placeholder {
  background: green !important;
}
:focus-visible {
    outline:none;
}
.eCharts_select{
	margin-left:20px;
		.el-select__wrapper{
			border-radius: 10px;
			border: 1px solid #dadee3;
			box-shadow:none;
		}
		
	}
	.vue-grid-layout{
		margin: -10px -20px 0;
  }
</style>
